#define _CRT_SECURE_NO_WARNINGS 1

#include"Stack.h"

void StackInit(ST* ps)
{
	assert(ps);
	ps->head = NULL;
	ps->top = 0;
	ps->capacity = 0;
}

void StackDestroy(ST* ps)
{
	assert(ps);
	free(ps->head);
	ps->head = NULL;
	ps->capacity = ps->top = 0;
}

void StackPush(ST* ps, Datatype x)
{
	assert(ps);
	if (ps->top == ps->capacity)
	{
		int newcapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
		Datatype* new = (Datatype*)realloc(ps->head ,sizeof(Datatype) * newcapacity);
		if (new == NULL)
		{
			perror("malloc error");
			exit(-1);
		}
		ps->capacity = newcapacity;
		ps->head = new;
	}
	ps->head[ps->top] = x;
	ps->top++;
}

void StackPop(ST* ps)
{
	assert(ps);
	assert(!Stackempty(ps));

	ps->top--;
}

Datatype StackRead(ST* ps)
{
	assert(ps);
	assert(!Stackempty(ps));

	return ps->head[ps->top-1];
}

bool Stackempty(ST* ps)
{
	assert(ps);
	return ps->top == 0;
}


bool isValid(char* s) 
{
    ST ps;
    StackInit(&ps);
    char* cur = s;
    while (*cur)
    {
        if (*cur == '('
            || *cur == '['
            || *cur == '{')
        {
            StackPush(&ps, *cur);
        }
        else
        {
            if ((StackRead(&ps) == '(' && *cur == ')')
                || (StackRead(&ps) == '[' && *cur == ']')
                || (StackRead(&ps) == '{' && *cur == '}'))
            {
                StackPop(&ps);
            }
            else
            {
                StackDestroy(&ps);
                return false;
            }
        }
        cur++;
    }
    if (Stackempty(&ps))
    {
        StackDestroy(&ps);
        return true;
    }
    else
    {
        StackDestroy(&ps);
        return false;
    }
    
}